/**
 *
 */
package com.engine.grm;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.util.EngineUtil;
import com.wfe.db.SessionUtil;
import com.wfe.generics.grm.GRMRequestHandlerImpl;
import com.wfe.mapping.client.Request;
import com.wfe.mapping.client.WfProjectTaskStatus;

/**
 * @author kareem_yehya
 * 
 */
public class RequestExecuter implements Runnable
{
	private static int fetchSize = 1;
	private static String fetchSizeParameter = "";

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	public void run()
	{
		System.out.println(" Request Executer Main Thead");
		while(true)
		{
			Session session = null;
			try
			{
				session = SessionUtil.getSession();

				List<Request> requestist = loadCreatedRequests(fetchSize, session);

				if(requestist.size() > 0)
				{
					for(Request request : requestist)
					{//
						executeRequest(request);
					}
				}

				Thread.sleep(500);
			}catch(Exception e)
			{
				e.printStackTrace();
			}finally
			{
				EngineUtil.closeSession(session);

			}

		}
	}

	private boolean executeRequest(Request request)
	{
		@SuppressWarnings("rawtypes")
		Class requestClass;
		try
		{
			requestClass = Class.forName(request.getRequestConf().getClassName());
		}catch(ClassNotFoundException e1)
		{
			System.out.println(" No Class Definition in DB For request Configuration Recid = " + request.getRequestConf().getRecid());
			System.out.println(" Task Configuration Missing Information Automatic Request ID = " + request.getRecid());
			e1.printStackTrace();
			return false;
		}

		GRMRequestHandlerImpl requestImpl = null;
		try
		{

			requestImpl = (GRMRequestHandlerImpl) requestClass.newInstance();
			requestImpl.setRecid(request.getRecid());
			requestImpl.setProcessingDate(new Date());
			requestImpl.setRequestConf(request.getRequestConf());
			requestImpl.setRequestId(request.getRequestId());
			requestImpl.setStoreDate(request.getStoreDate());
			requestImpl.setWfProjectTaskStatus(request.getWfProjectTaskStatus());
			requestImpl.execute();
			changeRequestAfterExecute(requestImpl);

			return true;
		}catch(Exception e)
		{
			if(requestImpl != null)
				System.out.println(" Finish execution With Error iside it of Request = " + requestImpl.getRecid());
			e.printStackTrace();
			return false;
		}

	}

	private void changeRequestAfterExecute(GRMRequestHandlerImpl requestImpl)
	{
		System.out.println("After Execution");

	}

	public static WfProjectTaskStatus getWfProjectTaskStatusByID(long i, Session session)
	{
		Criteria criteria = session.createCriteria(WfProjectTaskStatus.class);
		criteria.add(Restrictions.eq("recid", i));
		return (WfProjectTaskStatus) criteria.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	private List<Request> loadCreatedRequests(int maxresults, Session session)
	{
		List<Request> requestList = null;

		try
		{

			WfProjectTaskStatus wfProjectTaskStatus = getWfProjectTaskStatusByID(5l, session); // created
			Criteria criteria = session.createCriteria(Request.class);
			criteria.add(Restrictions.eq("wfProjectTaskStatus", wfProjectTaskStatus));
			if(maxresults > 0)
			{
				criteria.setMaxResults(maxresults);
			}
			requestList = criteria.list();
			return requestList;
		}catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		if(args.length > 0)
		{
			fetchSizeParameter = args[0];
			if(fetchSizeParameter != null && !fetchSizeParameter.equals(""))
			{
				fetchSize = Integer.parseInt(fetchSizeParameter);
				System.out.println("fetchSize = " + fetchSize);
			}
		}
		(new Thread(new RequestExecuter())).start();

	}

}
